package mx.com.sinformex.simbel.utils.export;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.services.Response;

import mx.com.sinformex.simbel.utils.IFileReporteExporter;

/**
 * @author Oscar Ivan Hernandez Ventura [ oscar at sinformex dot com dot mx]
 *
 * @version $ Id : JaspoerExporter.java , v 1.0 15/05/2009 angellore $
 */
public class JasperExporter implements IFileReporteExporter {

	public StreamResponse export(List<Map<String, Object>> rows, String templateFileName, Map<String, Object> parameters, java.sql.Connection conn, String outputFilename) {
		try {
			JasperReport report = JasperCompileManager.compileReport(templateFileName);
			JasperPrint print = JasperFillManager.fillReport(report, parameters, conn);
			byte[] bytes = JasperExportManager.exportReportToPdf(print);
			InputStream in = new ByteArrayInputStream(bytes);
			conn.close();
			return new PdfStreamResponse(in,outputFilename);
		} catch (JRException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	class PdfStreamResponse implements StreamResponse {
		
		private final String CONTENT_TYPE = "application/pdf";
		private final String EXTENSION = ".pdf";
		private String outputFilename;
		private InputStream in;

		public PdfStreamResponse(InputStream in, String outputFilename) {
			this.in = in;
			this.outputFilename = outputFilename;
		}
		
		public String getContentType() {
			return CONTENT_TYPE;
		}

		public InputStream getStream() throws IOException {
			return in;
		}

		public void prepareResponse(Response response) {
			response.setHeader("Content-Disposition", "attachment; filename=" + outputFilename + EXTENSION);
			response.setHeader("Expires", "0");
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");					
		}
		
	}

}
